<template>
  <div class="relation-ship">
    <el-dialog
      v-model="dialogTableVisible"
      :before-close="handleClose"
      :title="props.dialogTitle"
      fullscreen
    >
      <!-- <el-card v-if="activeNameFather === '2'" shadow="hover"> -->
      <el-card shadow="hover">
        <el-form ref="" :inline="true" class="demo-form-inline search">
          <el-form-item>
            <el-button @click="handleAdd()" :icon="Plus" plain type="primary">添加</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <div class="book-tab">
        <el-card shadow="hover">
          <div style="height: 550px" class="card-box">
            <el-auto-resizer>
              <template #default="{ height, width }">
                <el-table-v2
                  :columns="columns"
                  :data="tableModule.tableData"
                  :width="width"
                  :height="height"
                  fixed
                />
              </template>
            </el-auto-resizer>
          </div>
        </el-card>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary" @click="submitForm()">确定</el-button> -->
          <el-button @click="Cancel()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="tsx" setup>
import * as FormApi from '@/api/knowledge/character'
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Plus } from '@element-plus/icons-vue'
import { ElInput, ElSelect, Column, InputInstance } from 'element-plus'
import type { FunctionalComponent } from 'vue'
const router = useRouter()
const route = useRoute()
const props = defineProps({
  dialogTitle: String,
  operationalData: Object
})
const dialogTableVisible = ref(false)
const activeNameFather = ref()
// 初始表格数据
var initialTableData = []
// 当前行数据
const currentRowData = ref({})
const open = async (data, entityRelationshipData, activeName) => {
  tableModule.tableData = []
  console.log(data)
  currentRowData.value = data
  activeNameFather.value = activeName
  initialTableData = entityRelationshipData
  console.log('initialTableData', initialTableData)
  Object.assign(tableModule.tableData, entityRelationshipData)
  tableModule.tableData.forEach((item) => {
    Object.assign(item, { graphName: data.rowData.graphName })
    Object.assign(item, { graphId: data.rowData.graphId })
  })
  dialogTableVisible.value = true
  console.log(tableModule.tableData)
}
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('操作数据需点击保存，请确定是否保存？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}
const handleAdd = () => {
  // console.log(tableModule.tableData)
  console.log(props.operationalData)
  // Object.assign(tableModule.tableData, {
  //   graphName: '123',
  //   "startEntity": "陈赓",
  //   "startEntityId": "9704771948274b97a01367ea5613a2da",
  //   "startEntitySen": "中共中央军事部军事委员会内设有特务科，科长陈赓。",
  //   "relation": "职业职务",
  //   "endEntity": "科长",
  //   "endEntityId": "b40cbe0428cd4d8f936c152836c76d3c",
  //   "endEntitySen": "中共中央军事部军事委员会内设有特务科，科长陈赓。",
  //   "featureReleaseStatus": "NULL",
  //   "entityType": null,
  //   releaseStatus: 0
  // })
  const unshiftObject = {
    graphName: props.operationalData.graphName, // 所属图谱
    graphId: props.operationalData.graphId, // 所属ID
    startEntity: props.operationalData.eventName, // 起始节点名称
    startEntityId: props.operationalData.startEntityId, // 起始节点ID
    startEntitySen: props.operationalData.startEntitySen,
    relation: '请选择节点关系',
    endEntity: '请输入终止节点',
    endEntityId: '',
    endEntitySen: '',
    featureReleaseStatus: '', // 关系发布状态
    entityType: null
  }
  tableModule.tableData.unshift(unshiftObject)
  console.log(tableModule.tableData)
}
defineExpose({ open })
// 表格数据
const tableModule = reactive({
  tableData: [], // 表格数据
  currentPage: 1, // 表格分页：当前页
  pageSize: 10, // 表格分页：每页显示条目个数
  count: 1 // 表格分页：总记录数
})
// 节点关系数据
const nodeRelationshipData = [
  { value: '职业职务', label: '职业职务' },
  { value: '组织单位', label: '组织单位' }
]
type SelectionCellProps = {
  value: string
  selectValue: string
  intermediate?: boolean
  onChange: (value: string) => void
  forwardRef: (el: InputInstance) => void
}
const InputCell: FunctionalComponent<SelectionCellProps> = ({ value, onChange, forwardRef }) => {
  return <ElInput ref={forwardRef as any} onInput={onChange} modelValue={value} />
}
const SelectCell: FunctionalComponent<SelectionCellProps> = ({ selectValue }) => {
  return h(
    ElSelect,
    {
      modelValue: selectValue,
      'onUpdate:modelValue': (value: any, index: number) => {
        console.log('=log=onUpdate:modelValue=', value, index)
        selectValue = value
      },
      placeholder: '请选择节点关系',
      // clearable: true,
      style: 'width: 100%; padding: 20px 0px;',
      onChange: (value) => {
        console.log('onChange', value, selectValue)
      }
    },
    () => {
      const optionDom = []
      nodeRelationshipData.forEach((row) => {
        optionDom.push(h(ElOption, { label: row.label, value: row.value, disabled: false }))
      })
      return optionDom
    }
  )
}
// 弹窗取消
const Cancel = () => {
  dialogTableVisible.value = false
}
// 弹窗确定
const submitForm = async (data) => {
  console.log(data.rowData)
  console.log('initialTableData', initialTableData)
  console.log(tableModule.tableData)
  console.log('data.rowData.endEntityId', data.rowData.endEntityId)
  // 没有endEntityId字段，即为新添加的数据，调用新增接口
  if (!data.rowData.endEntityId) {
    const params = [
      {
        feature: data.rowData.endEntity,
        relation: data.rowData.relation,
        sen: '',
        entity: data.rowData.startEntity,
        graphName: data.rowData.graphName
      }
    ]
    FormApi.insertNeo4j(params).then((res) => {
      if (res.data === 0) return
      ElMessage({
        message: '新增成功',
        grouping: true,
        showClose: true,
        type: 'success'
      })
      getTableData()
    })
    return
  }
  // 否则为编辑数据，调用修改接口
  const params = [
    {
      graphName: data.rowData.graphName, // 所属图谱
      graphId: data.rowData.graphId, // 所属图谱ID
      featureCode: data.rowData.endEntityId, // 终止节点ID
      newFeature: data.rowData.endEntity, // 终止节点名称
      newRelation: data.rowData.relation, // 节点关系
      entityCode: data.rowData.startEntityId // 起始节点ID
    }
  ]
  FormApi.updateRelationAndFeatureByCode(params).then((res) => {
    if (res.data === 0) return
    ElMessage({
      message: '修改成功',
      grouping: true,
      showClose: true,
      type: 'success'
    })
    getTableData()
    // dialogTableVisible.value = false
  })
}
// 发布
const handleRelease = (data: any, type: boolean) => {
  console.log('发布')
  console.log(data.rowData.id)
  const params = {
    featureCode: data.rowData.endEntityId,
    // featureCode: currentRowData.value.rowData.id,
    graphName: route.query.graphName,
    featureReleaseStatus: 0 // 0取消发布 1发布
  }
  if (type) params.featureReleaseStatus = 1
  else params.featureReleaseStatus = 0
  FormApi.updateFeatureReleaseStatusByFeatureCode(params).then((res) => getTableData())
}
const getTableData = () => {
  console.log(currentRowData.value.rowData)
  let params
  if (currentRowData.value.rowData.entityType === 1) {
    params = {
      entity: currentRowData.value.rowData.entityName,
      graphName: route.query.graphName
    }
  } else if (currentRowData.value.rowData.entityType === 2) {
    params = {
      entity: currentRowData.value.rowData.eventName,
      graphName: route.query.graphName
    }
  }

  FormApi.findNeo4jByEntity(params).then((res) => {
    tableModule.tableData = []
    Object.assign(tableModule.tableData, res)
    tableModule.tableData.forEach((item) => {
      Object.assign(item, { graphName: currentRowData.value.rowData.graphName })
      Object.assign(item, { graphId: currentRowData.value.rowData.graphId })
    })
  })
}
// 删除
const handleDelete = (data: any) => {
  ElMessageBox.confirm('确定永久删除该条数据吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      console.log(data.rowData)
      const params = {
        entityCode: data.rowData.startEntityId,
        featureCode: data.rowData.endEntityId,
        graphName: data.rowData.graphName
      }
      FormApi.deleteRelationByEntityAndFeature(params)
        .then((res: any) => {
          if (res.data === 0) return
          ElMessage({
            type: 'success',
            grouping: true,
            showClose: true,
            message: '删除已完成'
          })
          getTableData()
        })
        .catch((error: any) => {
          ElMessage({
            message: error,
            grouping: true,
            showClose: true,
            type: 'error'
          })
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        grouping: true,
        showClose: true,
        message: '删除已取消'
      })
    })
}
const columns: Column<object>[] = [
  {
    key: 'graphName',
    title: '所属图谱',
    dataKey: 'graphName',
    width: 250,
    align: 'center',
    cellRenderer: ({ cellData: graphName }) => <div>{graphName}</div>
  },
  // {
  //   key: "graphId",
  //   title: "所属图谱ID",
  //   dataKey: "graphId",
  //   width: 300,
  //   align: "center",
  //   cellRenderer: ({ cellData: graphId }) => (
  //     <el-tooltip content={graphId}>{<span class="table-ellipsis">{graphId}</span>}</el-tooltip>
  //   )
  // },
  {
    key: 'startEntity',
    title: '起始节点',
    dataKey: 'startEntity',
    width: 250,
    align: 'center',
    cellRenderer: ({ cellData: startEntity }) => (
      <el-tooltip content={startEntity}>
        {<span class="table-ellipsis">{startEntity}</span>}
      </el-tooltip>
    )
  },
  // {
  //   key: "startEntityId",
  //   title: "起始节点ID",
  //   dataKey: "startEntityId",
  //   width: 300,
  //   align: "center",
  //   cellRenderer: ({ cellData: startEntityId }) => (
  //     <el-tooltip content={startEntityId}>{<span class="table-ellipsis">{startEntityId}</span>}</el-tooltip>
  //   )
  // },
  {
    key: 'relation',
    title: '节点关系',
    dataKey: 'relation',
    width: 250,
    align: 'center',
    cellRenderer: ({ rowData, column }) => {
      const onChange = (value: string) => {
        rowData[column.dataKey!] = value
      }
      const onEnterEditMode = () => {
        console.log(rowData)
        // editing为唯一属性，如多个列需要编辑时，需要使用新的属性名（editing2）
        rowData.editing = true
      }
      const onExitEditMode = () => (rowData.editing = false)
      const input = ref()
      const setRef = (el) => {
        input.value = el
        if (el) {
          el.focus?.()
        }
      }
      return (
        <SelectCell
          forwardRef={setRef}
          selectValue={rowData[column.dataKey!]}
          onChange={onChange}
          onBlur={onExitEditMode}
          onKeydownEnter={onExitEditMode}
        />
      )
      // return rowData.editing ? (
      //   <SelectCell
      //     forwardRef={setRef}
      //     selectValue={rowData[column.dataKey!]}
      //     onChange={onChange}
      //     onBlur={onExitEditMode}
      //     onKeydownEnter={onExitEditMode}
      //   />
      // ) : (
      //   <div class="table-v2-inline-editing-trigger" onClick={onEnterEditMode}>
      //     {rowData[column.dataKey!]}
      //   </div>
      // )
    }
  },
  {
    key: 'endEntity',
    title: '终止节点',
    dataKey: 'endEntity',
    width: 250,
    align: 'center',
    cellRenderer: ({ rowData, column }) => {
      const onChange = (value: string) => {
        rowData[column.dataKey!] = value
      }
      const onEnterEditMode = () => {
        console.log(rowData)
        rowData.editing2 = true
      }
      const onExitEditMode = () => (rowData.editing2 = false)
      const input = ref()
      const setRef = (el) => {
        input.value = el
        if (el) {
          el.focus?.()
        }
      }
      return (
        <InputCell
          forwardRef={setRef}
          value={rowData[column.dataKey!]}
          onChange={onChange}
          onBlur={onExitEditMode}
          onKeydownEnter={onExitEditMode}
        />
      )
      // return rowData.editing2 ? (
      //   <InputCell
      //     forwardRef={setRef}
      //     value={rowData[column.dataKey!]}
      //     onChange={onChange}
      //     onBlur={onExitEditMode}
      //     onKeydownEnter={onExitEditMode}
      //   />
      // ) : (
      //   <div class="table-v2-inline-editing-trigger" onClick={onEnterEditMode}>
      //     {rowData[column.dataKey!]}
      //   </div>
      // )
    }
  },
  // {
  //   key: "endEntityId",
  //   title: "终止节点ID",
  //   dataKey: "endEntityId",
  //   width: 300,
  //   align: "center",
  //   cellRenderer: ({ cellData: endEntityId }) => (
  //     <el-tooltip content={endEntityId}>{<span class="table-ellipsis">{endEntityId}</span>}</el-tooltip>
  //   )
  // },
  {
    key: 'featureReleaseStatus',
    title: '发布状态',
    dataKey: 'featureReleaseStatus',
    width: 200,
    align: 'center',
    cellRenderer: ({ cellData: featureReleaseStatus }) => (
      <>
        <el-tag v-show={Number(featureReleaseStatus) === 0} type="info">
          未发布
        </el-tag>
        <el-tag v-show={Number(featureReleaseStatus) === 1} type="primary">
          已发布
        </el-tag>
      </>
    )
  },
  {
    key: '操作',
    title: '操作',
    cellRenderer: (data) => (
      <>
        <el-button
          v-show={Number(data.rowData.featureReleaseStatus) === 0}
          onClick={handleRelease.bind(this, data, true)}
          type="primary"
          size="small"
        >
          发布
        </el-button>
        <el-button
          v-show={Number(data.rowData.featureReleaseStatus) === 1}
          onClick={handleRelease.bind(this, data, false)}
          type="info"
          size="small"
        >
          取消发布
        </el-button>
        <el-button onClick={submitForm.bind(this, data)} type="success" size="small">
          保存
        </el-button>
        <el-button onClick={handleDelete.bind(this, data)} type="danger" size="small">
          删除
        </el-button>
      </>
    ),
    width: 300,
    align: 'center'
  }
]
</script>
<style lang="scss" scoped>
.relation-ship {
  // 覆盖默认overflow: auto样式，防止出现无效的滚动条
  ::v-deep(.el-dialog) {
    overflow: hidden !important;
  }

  .book-tab {
    margin-top: 20px;
  }

  .search {
    .el-form-item {
      margin: 0 32px 0 0;
    }
  }

  .table-v2-inline-editing-trigger {
    border: 1px transparent dotted;
    padding: 4px;
  }

  .table-v2-inline-editing-trigger:hover {
    border-color: var(--el-color-primary);
  }

  ::v-deep(.table-ellipsis) {
    word-break: break-all; // 允许在单词内换行
    text-overflow: ellipsis; // 显示省略符号来代表被修剪的文本
    overflow: hidden;
    white-space: nowrap; // 不换行控制单行文本
  }

  ::v-deep(.el-dialog__body) {
    // padding: 0;
  }
}

.card-box {
  margin-top: 20px;
}
</style>
